package com.cecw.Utils;

/**
 * @author linlingxin
 * @date 2024/5/24 13:44
 */

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * @author linlingxin
 * @date 2024/5/24 15:41
 */
public class GetBearerToken {

    public static String getToken(String tokenUrl,String clientId,String clientSecret,String username,String password) {

        try {
            // 创建Url连接
            URL url = new URL(tokenUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setDoOutput(true);

            // 设置请求体内容
            String requestBody = "grant_type=password&username=" + username
                    + "&password=" + password
                    + "&client_id=" + clientId
                    + "&client_secret=" + clientSecret;

            // 把请求体内容和请求绑定
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = requestBody.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 检查是否响应成功
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 解析响应
                /**
                 * conn.getInputStream()：获取HTTP连接的输入流，这个流包含了服务器的响应数据。
                 * new InputStreamReader(conn.getInputStream(), "utf-8")：
                 *      用InputStreamReader将字节流转换为字符流，并指定字符编码为UTF-8。
                 */
                try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }

                    // 解析响应的Json
                    JSONObject jsonResponse = new JSONObject(response.toString());
                    String accessToken = jsonResponse.getString("access_token");
                    return accessToken;
                }
            } else {
                System.out.println("Failed to obtain token. HTTP response code: " + responseCode);
                try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "utf-8"))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    return "Error response: "+response.toString();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

